<template>
  <view>
    <!-- @scrolltolower="onScrollToLower" -->
    <uni-transition ref="ani" :mode-class="['fade', 'slide-top']" :show="show">
      <scroll-view ref="scrollView" class="scroll-view" scroll-y>
        <view class="cu-chat">
          <!-- 查看历史消息 -->
          <view class="cu-info round" @click="onClickTop">查看历史消息</view>
          <!-- 遍历历史 -->
          <view v-for="(item, index) in historyList" :key="index">
            <!-- 聊天和头像 -->
            <view :class="[ item.identity ? 'cu-item self' : 'cu-item']">
              <!-- 对方头像 -->
              <view class="cu-avatar round lg" :style="{'background-image': 'url(' + receiveUser.avatar + ')'}"
                v-if="item.identity === 0"></view>
              <!-- 气泡 -->
              <view class="main">
                <view :class="[ item.identity ? 'content bg-green shadow' : 'content shadow']">
                  <text>{{item.msg}}</text>
                </view>
              </view>
              <!-- 我方头像 -->
              <view class="cu-avatar round lg" :style="{'background-image': 'url(' + sendUser.avatar + ')'}"
                v-if="item.identity !== 0"></view>
              <!-- 时间 -->
              <view class="date"> {{item.sendTime != null ? item.sendTime : ""}} </view>
            </view>
          </view>
        </view>
      </scroll-view>

    </uni-transition>

    <!-- 消息弹出框 -->
    <view>
      <!-- 提示信息弹窗 -->
      <uni-popup ref="message" type="message">
        <uni-popup-message :type="msgType" :message="msgContent" :duration="2000"></uni-popup-message>
      </uni-popup>
    </view>

    <!-- 发送信息 -->
    <view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
      <view class="action">
        <text class="cuIcon-sound text-grey"></text>
      </view>
      <input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"
        @focus="InputFocus" @blur="InputBlur" v-model="content"></input>
      <view class="action">
        <text class="cuIcon-emojifill text-grey"></text>
      </view>
      <button class="cu-btn bg-green shadow" @click="onsubmit">发送</button>
    </view>

  </view>
</template>

<script>
  // 引入websocket
  import wsRequest from '../../static/js/websocket.js'
  import {
    mapState
  } from 'vuex'
  export default {
    data() {
      return {
        InputBottom: 0,
        msgType: "",
        msgContent: "",
        show: true,
        loading: false,
        content: '',
        ws: {},
        sendUser: {
          id: null,
          avatar: "",
        },
        defaultAvatar: '', // 默认图片地址
        receiveUser: {}, // 请求跳转对象
        historyList: [],
        queryObj: {
          receiveId: '',
          // 页码值
          pageNum: 1,
          // 每页显示多少条数据
          pageSize: 10,
        },
        total: 0,
        // 是否在加载中
        isloading: false,
        hasNext: true
      };
    },
    computed: {
      // 2. 从 m_user 模块中导入需要的 token 字符串
      ...mapState('m_user', ['patientInfo', 'userInfo']),
    },

    beforeDestroy() {
      this.ws.is_open_socket = false;
      this.ws.close()
    },

    onLoad(options) {
      // 为默认图片路径赋值 
      if (this.$staticUrl) {
        this.defaultAvatar = this.$staticUrl + 'my-icon-def-avatar.png';
      } else {
        console.error('staticUrl 未定义');
      }
      // 展示提示消息
      this.msgType = "warn";
      this.msgContent = "当前医生将在24小时内回复您";
      this.$refs.message.open();

      // 封装receiveUser信息
      const {
        name,
        avatar,
        id
      } = options;
      this.receiveUser = {
        name,
        avatar,
        id
      };
      uni.setNavigationBarTitle({
        title: options.name
      })
      // console.log(this.receiveUser)
      if (!this.receiveUser.avatar) {
        this.receiveUser.avatar = this.defaultAvatar;
      }

      // TODO获取sendUser信息
      this.sendUser.id = this.patientInfo.patientId;
      this.sendUser.avatar = this.userInfo.avatar ? this.userInfo.avatar : defaultAvatar;

      this.init();
      this.clearNoneVisit();
    },

    methods: {
      // 跳转到底部
      scrollToBottom() {
        this.$nextTick(() => {
          uni.pageScrollTo({
            scrollTop: 9999, // 设置一个很大的值，确保滚动到底部
            duration: 300, // 滚动动画的时长
          });
        })
      },

      // 把全部未读改为已读
      async clearNoneVisit() {
        let sendId = this.sendUser.id;
        let receiveId = this.receiveUser.id
        await uni.$http.get(`/chat/clear/${receiveId}/${sendId}`)
      },
      // 初始化
      async init() {
        // TODO 登陆完成以后从本地拿取sendId
        const sendId = this.sendUser.id;
        this.queryObj.receiveId = this.receiveUser.id // 发送者的Id
        const wsuri = this.$websocketUrl + sendId;
        this.ws = new wsRequest(wsuri, 30000);
        this.ws.getMessage((res) => {
          // 处理心跳逻辑
          let data = res.data
          console.log(data);
          if (data == "$pong$") {
            return;
          }
          // 处理监听消息逻辑
          this.displayContent(data);
          this.msgType = "info";
          this.msgContent = "您收到一条新消息";
          this.$refs.message.open();
        });
        // 发送请求
        const {
          data: res
        } = await uni.$http.get('/chat/history', this.queryObj)
        if (res.code !== 200) return uni.$showMsg()
        this.historyList = res.data.reverse();
      },

      // 显示对方发送内容到页面上
      displayContent(msg) {
        const respData = JSON.parse(msg);
        let identity = 0;
        let content = "";
        // 判断信息是否正确
        if (respData.code != 200) {
          identity = 1;
          content = respData.msg;
        } else {
          identity = 0;
          content = respData.data;
        }
        // 获取头像
        const receiveAvatar = this.receiveUser.avatar
        const now = new Date();
        const time = `${now.getHours()}:${now.getMinutes()}`;
        let contentObj = {
          avatar: receiveAvatar,
          sendTime: time,
          msg: content,
          identity: identity
        }
        this.historyList = [...this.historyList, ...[contentObj]]
      },

      // 触顶的事件
      onClickTop() {
        // 判断是否还有下一页数据
        if (!this.hasNext) {
          return uni.$showMsg('数据加载完毕！')
        }
        // 判断是否正在请求其它数据，如果是，则不发起额外的请求
        if (this.isloading) return
        // 让页码值自增 +1
        this.queryObj.page += 1
        // 重新获取列表数据
        this.getHistoryList()
      },

      // 获取历史信息并封装进的信息
      async getHistoryList() {
        // ** 打开节流阀
        this.isloading = true
        this.show = false;
        // 发起请求
        const {
          data: res
        } = await uni.$http.get('/chat/history', this.queryObj)
        // ** 关闭节流阀
        this.isloading = false
        if (res.code !== 200) return uni.$showMsg()
        // 为数据赋值：通过展开运算符的形式，进行新旧数据的拼接 
        this.historyList = [...res.data.reverse(), ...this.historyList]
        this.show = true;
        this.hasNext = res.data.length < this.queryObj.pageSize;
      },

      // 提交当前消息
      onsubmit() {
        if (this.loading || !this.content) {
          return
        }
        // 处理发送消息逻辑
        // 封装content信息
        let replyContent = {
          content: this.content,
          receiveId: this.receiveUser.id
        }
        // 发送send请求
        this.loading = true
        this.ws.send(JSON.stringify(replyContent))
        // 在页面中显示出来 封装为history中的对象
        this.displayMyContent()
        // 清空content
        this.content = ''
        this.replyContent = {}
        // 使用 $nextTick 确保 DOM 更新完毕后再滚动到底部
        this.scrollToBottom();
        this.loading = false
      },

      // 展示自己的消息
      displayMyContent() {
        // 现在先展示默认数据 等到登陆以后完成后续逻辑
        let sendAvatar = this.sendUser.avatar;
        const now = new Date();
        const time = `${now.getHours()}:${now.getMinutes()}`;
        let contentObj = {
          avatar: sendAvatar,
          sendTime: time,
          msg: this.content,
          identity: 1
        }
        this.historyList = [...this.historyList, ...[contentObj]]
      },
      // 失去焦点函数
      InputBlur() {
        if (process.env.NODE_ENV === 'production') {
          this.InputBottom = 0;
        }
        // console.log(this.content)
      },

      // 聚焦函数
      InputFocus() {
        if (process.env.NODE_ENV === 'production') {
          console.log('到达');
          this.InputBottom = 300;
        }
        // console.log(this.content)
      }
    }
  }
</script>

<style lang="scss">
  .cu-chat {
    // padding-bottom: 50px;
    margin-bottom: 50px;
  }

  .cu-bar {}
</style>